package cn.im.thread;

import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 建议使用ThreadPoolExecutor代替Executors来创建线程池，以此规避资源耗尽的风险
 * Executors 会因大量请求or创建大量线程导致资源耗尽
 */
public class ThreadPoolExecutorDemo {
    private static final int CORE_POOL_SIZE = 5;   //核心线程数（线程池的基本大小）
    private static final int MAX_POOL_SIZE = 10;    //最大线程数:线程池允许创建的最大线程数
    private static final int QUEUE_CAPACITY = 100;  //任务队列最大容量
    private static final Long KEEP_ALIVE_TIME = 1L;     //空闲线程最大生存时间


    public static void main(String[] args) {

        //通过ThreadPoolExecutor构造函数自定义参数创建
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy());

        for (int i = 0; i < 10; i++) {
            //创建WorkerThread对象（WorkerThread类实现了Runnable 接口）
            Runnable worker = new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " Start. Time = " + new Date());
                    processCommand();
                    System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());
                }
                private void processCommand() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            //执行Runnable
            executor.execute(worker);
        }
        //终止线程池
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}
